#include <iostream>
#include <gflags/gflags.h>
#include "etcd.hpp"
#include <thread>
#include "main.pb.h"
#include "./../../../common/log.hpp"
#include <unistd.h>

#include "channel.hpp"



DEFINE_bool(run_mode, false, "程序运行模式 false-调试 true-发布");
DEFINE_string(log_file, "log.txt", "发布模式下 输出文件的，文件名");
DEFINE_int32(log_level, 0 , "日志等级");

const std::string host = "http://127.0.0.1:2379";

void online(const std::string& key, const std::string& val)
{
    DEBUG_LOG("line-上线服务{}-{}", key, val);
}

void offline(const std::string& key, const std::string& val)
{
    DEBUG_LOG("line-下线服务{}-{}", key, val);
}


int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    

    // 1, 构建rpc信道管理对象
    auto sm = std::make_shared<ServiceManager>();
    sm->declared("/service/echo");
    auto put_cb = std::bind(&ServiceManager::Online, sm.get(), std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&ServiceManager::Offline, sm.get(), std::placeholders::_1, std::placeholders::_2);

    // 2, 构建服务发现对象
    Discovery::ptr  pclient = make_shared<Discovery>(host,"/service", put_cb, del_cb);

    while(1)
    {
        // 3, 通过rpc信道管理对象  获取提供echo服务的信道
        auto channel = sm->choose("/service/echo");
        if(channel == nullptr)
        {
            sleep(1);
            continue;

        }
        // 4, 发起echoepr调用
        example::EchoService_Stub stub(channel.get());

        brpc::Controller* cnt = new brpc::Controller();
        example::EchoRequest* req = new example::EchoRequest();
        example::EchoResponse* rsp = new example::EchoResponse();

        req->set_message("hello brpc");
        stub.Echo(cnt, req, rsp, nullptr);
        if(cnt->Failed() == 1)
        {
            std::cout << "rpc调用失败" << std::endl;
            continue;
        }
        std::cout << "收到响应： " << rsp->message() << std::endl;
        delete cnt;
        delete rsp;
        delete req;
        sleep(1);
    }

    return 0;
}